cmake_minimum_required(VERSION 3.20.0)
project(pg_cascades VERSION 0.1.0 LANGUAGES C CXX)

set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS on)
set(CMAKE_POSITION_INDEPENDENT_CODE TRUE)
enable_testing()

if(NOT CMAKE_BUILD_TYPE)
    set(CMAKE_BUILD_TYPE "RelWithDebInfo")
endif(NOT CMAKE_BUILD_TYPE)
message(STATUS "Build type: ${CMAKE_BUILD_TYPE}")

list(APPEND CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake)

find_package(PostgreSQL REQUIRED)

set(PostgreSQL_COMPILE_OPTIONS
  ${PostgreSQL_COMPILE_OPTIONS}
    -Werror
    -Wall
    -fvisibility=hidden
    -fvisibility-inlines-hidden
)

# ENABLE_NLS is controlled by the pg, confilicts with std::format
set(PostgreSQL_COMPILE_DEFINE ${PostgreSQL_COMPILE_DEFINE} -DENABLE_NLS)

if (${CMAKE_BUILD_TYPE} STREQUAL "Debug")
    set(PostgreSQL_COMPILE_DEFINE ${PostgreSQL_COMPILE_DEFINE} -DPLAN_DEBUG=1)
  else()
    set(PostgreSQL_COMPILE_DEFINE ${PostgreSQL_COMPILE_DEFINE} -DPLAN_DEBUG=0)
endif()

option(ENABLE_COVERAGE "Enable coverage reporting" OFF)

if(ENABLE_COVERAGE)
  if(NOT "${CMAKE_BUILD_TYPE}" STREQUAL "Debug")                      # If coverage is required on non-DEBUG builds,
    message(FATAL_ERROR "Coverage requires a debug build type!")      # Then error out.
  endif()
  set(PostgreSQL_COMPILE_OPTIONS ${PostgreSQL_COMPILE_OPTIONS} --coverage)
  set(PostgreSQL_LINK_OPTIONS ${PostgreSQL_LINK_OPTIONS} --coverage)
endif()
message(STATUS "Coverage ${ENABLE_COVERAGE}")

file(
  GLOB_RECURSE
  OPTIMIZER_SRCS
  CONFIGURE_DEPENDS
    ${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp 
)

file(
  GLOB_RECURSE
  OPTIMIZER_TEST_SRCS
  CONFIGURE_DEPENDS
    ${CMAKE_CURRENT_SOURCE_DIR}/test/test/*.cpp
)

add_postgresql_extension(
  pg_cascades
  VERSION 1.0
  SOURCES ${OPTIMIZER_SRCS}
  HEADERS ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/test
  SCRIPTS src/pg_cascades--1.0.sql
  TEST_SOURCE ${OPTIMIZER_TEST_SRCS}
)

# clang-format
add_custom_target(format
  COMMAND git diff --name-only --diff-filter=d --cached '*.cpp' '*.h' | xargs clang-format -i
  WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
)

file(
  GLOB_RECURSE
  CHECK_SRCS
  CONFIGURE_DEPENDS
    ${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp 
    ${CMAKE_CURRENT_SOURCE_DIR}/test/test/*.cpp
    ${CMAKE_CURRENT_SOURCE_DIR}/include/*.h
    ${CMAKE_CURRENT_SOURCE_DIR}/test/*.h
)

# clang-format
add_custom_target(check-format
  COMMAND clang-format --style=file --dry-run -Werror -i  ${CHECK_SRCS}
  VERBATIM
)

# clang-tidy
# run-clang-tidy -p build/Debug -config-file=./.clang-tidy 
add_custom_target(check-tidy
  COMMAND run-clang-tidy -p ${CMAKE_BINARY_DIR} -config-file=${CMAKE_CURRENT_SOURCE_DIR}/.clang-tidy
  VERBATIM
)